package com.example.demo;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.val;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/Request")

public class RequestController {
    @RequestMapping("/request")
    public String request(String keyword){
        return "关键词："+keyword;
    }
    @RequestMapping("/r")
    public String r(@RequestParam("q") String keyword){
        return "关键词："+keyword;
    }
    @RequestMapping("/r2")
    public String list(@RequestParam  List<String> list){
        return "返回值:"+list;
    }
    //传一个Json
    @RequestMapping("/r3")
    public String r3(@RequestBody User user){
        return user.toString();
    }
    //传一个文件并保存到本地
    @RequestMapping("/r4")
    public String r4(MultipartFile file) throws IOException {
        System.out.println(file.getOriginalFilename());
        file.transferTo(new File("D:\\JavaProject",file.getOriginalFilename()));
        return "文件获取成功";
    }
    //从url中获取路径参数
    @RequestMapping("/article/{Userid}/{type}")
    public String r5(@PathVariable Integer Userid,@PathVariable int type){
        return "userid:"+Userid+"type:"+type;
    }

    //设置session
    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute("name","李飒");
        session.setAttribute("age",20);
        return "设置成功";
    }
    //获取session  方法1
    @RequestMapping("/getSession1")
    public String getSession(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if (session==null){
            return "不存在";
        }else {
            String attributeNames = (String)session.getAttribute("name");
            return "name: "+attributeNames;

        }
    }
    //方法2
    @RequestMapping("/getSession2")
    public String getSession2(HttpSession session){
            String attributeNames = (String)session.getAttribute("name");
            return "name: "+attributeNames;
    }
    //方法3
    @RequestMapping("/getSession3")
    public String getSession2(@SessionAttribute("age") String name){

        return "name: "+name;
    }


}
